package Dao;

import java.io.Serializable;
import java.util.List;

import webapp.Dispetcher;
import table.DispetcherTable;

import AbstrDao.AbstractDao;

public class DispetcherDao extends AbstractDao<DispetcherTable, Dispetcher> {

	public DispetcherDao(final String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public void saveNew(final Dispetcher newDispetcher) {
		// set ID
		newDispetcher.setId(getNextId());
		// get existing data
		final DispetcherTable DispetcherTable = deserializeFromXml();
		// add new row
		DispetcherTable.getRows().add(newDispetcher);
		// save data
		serializeToXml(DispetcherTable);
	}

	@Override
	public void update(final Dispetcher entity) {
		// get existing data
		final DispetcherTable DispetcherTable = deserializeFromXml();
		// find by ID
		for (final Dispetcher row : DispetcherTable.getRows()) {
			if (row.getId().equals(entity.getId())) {
				// found!!!
				// copy data
				row.setwater(entity.getwater());
				row.setelectricity(entity.getelectricity());
				row.setquench(entity.getquench());
				row.setheating(entity.getheating());
				break;
			}
		}
		// save updated table
		serializeToXml(DispetcherTable);
	}

	@Override
	public Dispetcher get(final Serializable id) {
		// get existing data
		final DispetcherTable DispetcherTable = deserializeFromXml();
		// find by ID
		for (final Dispetcher row : DispetcherTable.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}

	@Override
	public List<Dispetcher> getAll() {
		// get existing data
		final DispetcherTable DispetcherTable = deserializeFromXml();
		return DispetcherTable.getRows();
	}

	@Override
	public void delete(final Serializable id) {
		// get existing data
		final DispetcherTable DispetcherTable = deserializeFromXml();
		// find by ID
		Dispetcher toBeDeleted = null;
		for (final Dispetcher row : DispetcherTable.getRows()) {
			if (row.getId().equals(id)) {
				// found!!!
				toBeDeleted = row;
				break;
			}
		}
		// remove from list
		DispetcherTable.getRows().remove(toBeDeleted);
		// save updated table
		serializeToXml(DispetcherTable);
	}

	@Override
	protected Class<DispetcherTable> getTableClass() {
		return DispetcherTable.class;
	}

}
